package com.itheima.controller.ValidateCode;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.SMSUtils;
import com.itheima.common.utils.ValidateCodeUtils;
import com.itheima.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * 验证码操作
 */
@RestController
@RequestMapping("/validatecode")
@Slf4j
public class ValidateCodeController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MailService mailService;

    /**
     * 体检预约系统验证码
     * @param telephone
     * @return
     */
    @PostMapping("/send4Order")
    public Result send4Order(@RequestParam String telephone) {
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        try {
             log.info("验证码为" + validateCode);
            //SMSUtils.sendMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
            //发送邮箱
            mailService.sendTextMailMessage("915121666@qq.com","Code",validateCode.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("验证码发送失败");
        }
        redisTemplate.opsForValue().set(telephone+ RedisMessageConstant.SENDTYPE_ORDER,validateCode.toString(),5, TimeUnit.MINUTES);
        return Result.success("验证码发送成功");
    }

    /**
     * 手机号快速登录发送验证码
     * @param telephone
     * @return
     */
    @GetMapping("/send4Login")
    public Result send4Login(@RequestParam String telephone) {
        Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
        try {
             log.info("验证码为" + validateCode);
            //SMSUtils.sendMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
            //发送邮箱
            mailService.sendTextMailMessage("915121666@qq.com","Code",validateCode.toString());

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("验证码发送失败");
        }
        redisTemplate.opsForValue().set(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,validateCode.toString(),5, TimeUnit.MINUTES);
        return Result.success("验证码发送成功");
    }
}
